﻿using System;
using System.Collections.Generic;
using System.Linq;
using MvcContrib.UI.Grid;
using MvcContrib.Sorting;
using MvcContrib.Pagination;

namespace WeBlog.Models
{
    public abstract class GridModel<T>
    {
        private IQueryable<T> _superset;        

        protected GridModel(GridSettings settings )
        {
            Settings = settings;                        
        }            

        public GridSortOptions GridSortOptions {
            get
            {
                return new GridSortOptions
                {
                    Column = String.IsNullOrWhiteSpace(Settings.Column) ? Settings.DefaultSortColumn : Settings.Column,
                    Direction = Settings.Direction
                };
            }           
        }

        public GridSettings Settings { get; set; }        

        public IPagination PagingInfo { 
            get { return Data as IPagination; } 
        }        

        public abstract IQueryable<T> GetSuperSet();

        public IEnumerable<T> Data
        {
            get
            {
                if (_superset == null)
                    _superset = GetSuperSet();
                
                var options = GridSortOptions;
                var ordered = _superset.OrderBy(options.Column, options.Direction);
                return ordered.AsPagination(Settings.Page ?? 1, Settings.PageSize ?? Settings.DefaultPageSize);                
            }
        }               
    }

    public class GridSettings
    {
        public string DefaultSortColumn { get; set; }
        public int DefaultPageSize { get; set; }
        public SortDirection Direction { get; set; }
        public string Column { get; set; }
        public int? Page { get; set; }
        public int? PageSize { get; set; }

        public GridSettings()
        {
            DefaultPageSize = 10;
            Page = 1;
            Direction = SortDirection.Ascending;
        }

        public GridSettings( string defaultSortColumn ) : this()           
        {
            DefaultSortColumn = defaultSortColumn;
        }
    }
}
